/**
 * 中国居民身份证号码解析
 *
 * @author Yufe
 * @version 1.0
 */
const dayjs = require("dayjs");

/**
 * 身份证加权因子
 */

const wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
/**
 * 身份证校验码
 */
const vd = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];
/**
 * 身份证校验正则式
 */
const reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;

/**
 * 身份证校验器
 * @param {String} value 身份证号码
 * @returns {object} 例如：{success: true|false, message: "xxx"}
 */
const validate = (value = "") => {
  if (value && reg.test(value)) {
    let sum = 0;
    let arrays = value.split("");
    for (let i = 0, len = arrays.length - 1; i < len; i++) {
      sum += arrays[i] * wi[i];
    }
    if (arrays[17].toUpperCase() === vd[sum % 11]) {
      return {
        success: true, message: "成功"
      };
    }
    return {
      success: false, message: "无效的身份证号码",
    };
  }
  return {
    success: false, message: "无效的身份证号码",
  };
};

/**
 * 解析身份证号码
 * @param {String} value 身份证号码
 * @returns {object} 例如: {success: true, message: '', region: xxx, born: 1900-01-01, sex: 0|1, age: 34}
 */
const resolve = (value) => {
  let res = validate(value);
  const {success} = res;
  if (success) {
    const born = dayjs(value.substring(6, 14), "YYYYMMDD");
    const sexIndex = value.length === 15 ? 14 : 16;
    const sexValue = value.substring(sexIndex, sexIndex + 1);
    res = {
      ...res, sex: sexValue % 2, age: (dayjs().diff(born, "days") / 365).toFixed(0), born: born.format("YYYY-MM-DD"), region: value.substring(0, 6),
    };
  }
  return res;
};

module.exports = {
  resolve, validate
};
